package snail.controllers;

import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.validation.BindException;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.SimpleFormController;

import snail.hibernate.util.HibernateUtil;
import org.hibernate.Session;
import snail.misc.PreparedModelAndView;
import snail.model.Article;
import snail.model.Category;
import snail.model.User;

public class CreateArticleFormController extends SimpleFormController {

    @Override
    protected void doSubmitAction(Object command) throws Exception {
        throw new UnsupportedOperationException("Not yet implemented");
    }

    @Override
    protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response) throws Exception {
        if (request.getSession().getAttribute("user") == null) {
            return new UserController().login(request, response, "../articles/create");
        }

        ModelAndView mav = new PreparedModelAndView(request);
        ModelAndView mv = super.handleRequestInternal(request, response);
        if (mv != null) {
            mv.addAllObjects(mav.getModelMap());
            mv.setViewName("articles/createForm");
        }
        return mv;
    }

    @Override
    protected ModelAndView onSubmit(
            HttpServletRequest request,
            HttpServletResponse response,
            Object command,
            BindException errors) throws Exception {

        Session session = HibernateUtil.getSessionFactory().getCurrentSession();

        User user = (User) request.getSession().getAttribute("user");
        Category category = (Category) session.load(Category.class, Integer.parseInt(request.getParameter("categoryId")));
        Article article = (Article) command;
        Calendar c = new GregorianCalendar();
        c.add(Calendar.DAY_OF_MONTH, 7);

        article.setExpireDate(c.getTime());
        article.setCreateDate(new Date());

        // lägg till artikeln i användarens artiklar/rätt kategori
        article.setCreatorUser(user);
        article.setCategory(category);

        session.save(article);

        
        response.sendRedirect("index");

        return null;
    }
}
